package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var UP = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var Conns []*websocket.Conn

func handler(w http.ResponseWriter, r *http.Request) {
	conn, err := UP.Upgrade(w, r, nil)
	fmt.Println("conn", conn)
	if err != nil {
		return
	}
	fmt.Println(conn.RemoteAddr())

	Conns = append(Conns, conn)

	for {
		m, p, e := conn.ReadMessage()
		if e != nil {
			fmt.Println(e)
			break
		}
		for _, conn := range Conns {
			// 广播
			err := conn.WriteMessage(m, []byte("你想问的是:"+string(p)+"吗？"))
			if err != nil {
				fmt.Println(err)
			}
		}
		fmt.Println("收到消息", m, string(p))
		//conn.WriteMessage(m, []byte("你想问的是:"+string(p)+"吗？"))
	}
	defer conn.Close()
	log.Println("服务关闭")
}

func main() {
	fmt.Println("websocket")
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}
